package com.javajun.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javajun.custom.JqGridParm;
import com.javajun.custom.JqGridUtils;
import com.javajun.entity.Customer;
import com.javajun.entity.Empower;
import com.javajun.entity.Enterprise;
import com.javajun.entity.EnterpriseAdmin;
import com.javajun.entity.UserRole;
import com.javajun.form.J2EnpriseAdminForm;
import com.javajun.form.JCustomerForm;
import com.javajun.service.CustomerService;
import com.javajun.service.EnterpriseAdminService;
import com.javajun.service.UserRoleService;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private EnterpriseAdminService enterpriseAdminService;
    @Autowired
    private UserRoleService userRoleService;
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @RequestMapping(value = "/manage")
    public String manage(ModelMap map) {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        User user = (User) auth.getPrincipal();
        System.out.println("Username："+user.getUsername());
        System.out.println("Password:"+user.getPassword());
        return "customer/manage";
    }
    
    @RequestMapping(value = "getlist", method=RequestMethod.POST)
    // 返回json数据
    @ResponseBody
    public Object getList(JqGridParm parm) {
        Pageable pageable = parm.buildPageable();
        Enterprise enterprise = findEnterpriserByUsername();
        Page<Customer> page = null;
        if (!parm.getSearch()) {
            page = customerService.findByEnterprise(enterprise, pageable);
        } else {
            // page = enterpriseService.findAll(parm.buildSpec(), pageable);
        }
        HashMap<String, Object> pageResult = JqGridUtils.getPageResult(page);
        return pageResult;
    }
    
    @RequestMapping(value = { "/add", "/edit" }, method = RequestMethod.POST)
    @ResponseBody
    public Object addAndEdit(ModelMap map, String[] id, JCustomerForm form) {
        String mess = "";
        if (form.getOper().equals("add")) {
            Integer customerId = null;
            save(customerId, form);
            mess = "Add is OK!";
        } else if (form.getOper().equals("edit")) {
            Integer customerId = null;
            for (int i = 0; i < id.length; i++) {
                System.out.println(id[i]);
                customerId = Integer.parseInt(id[i]);
            }
            save(customerId, form);
           // save(enterpriseId, form);
        } else if (form.getOper().equals("del")) {
            for (int i = 0; i < id.length; i++) {
                delete(map, Integer.parseInt(id[i]));
                System.out.println("删除用户id：" + id[i]);
            }
            mess = "Delete is OK!";
            System.out.println(mess);
        }
        return mess;
    }

    /**
     * Delte 通过Id删除一个用户
     * @param map
     * @param id
     */
    private void delete(ModelMap map, Integer id) {
        if (id != null) {
            customerService.deleteById(id);
        }
        
    }

    public void save(Integer id, JCustomerForm form) {
        Customer customer = new Customer();
        if (id !=null) {
            customer = customerService.findById(id);
        }
        
        // 1.用户名
        // 2.名字
        // 3.备注
        // 4.密码(默认1111)
        
        if (StringUtils.hasText(form.getUsername())) {
            customer.setUsername(form.getUsername());
        }
        
        if (StringUtils.hasText(form.getName())) {
            customer.setName(form.getName());
        }
        
        if (StringUtils.hasText(form.getRemarks())) {
            customer.setRemarks(form.getRemarks());
        }
        
        customer.setPassword(encoder.encode("1111"));
        
        // 绑定租户
        // 1.获取当前租户
        // 2.为新增用户设置租户
        
        Enterprise enterprise = findEnterpriserByUsername();
        customer.setEnterprise(enterprise);
        
        // 用户角色
        if (customer.getRoles() == null) {
            List<UserRole> roles = new ArrayList<>();
            customer.setRoles(roles);
        }
        customer.getRoles().add(userRoleService.findByCode("ROLE_CUSTOMER"));
        
        // 保存
        customerService.save(customer);
    }
    
    // 通过租户管理员的用户名查找到一个租户对象
    public Enterprise findEnterpriserByUsername() {
        String username = enterpriseAdminService.getCurrentUsername();
        EnterpriseAdmin enterpriseAdmin = enterpriseAdminService.findByUsername(username);
        return enterpriseAdmin.getEnterprise();
    }
    
    @RequestMapping(value="/check")
    @ResponseBody
    public String check(String username) {
        Customer entity = customerService.findByUsername(username);
        if (entity == null) {
            return "ok";
        }
        return "on";
    }
}
